<template>
  <!--  <the-nav-bar custom>-->
  <!--    <template #right>-->
  <!--      &lt;!&ndash; <van-icon name="search" size="16" @click="onClickSearch" color="#fff"/> &ndash;&gt;-->
  <!--      <svg-icon name="login-out" class="login-out" color="#fff" @click="loginOut" />-->
  <!--    </template>-->
  <!--  </the-nav-bar>-->

  <div class="page-view overflow-y flex-col">
    <div class="flex-1 overflow-y">
      <van-form ref="formRef" label-width="80" required="auto">
        <van-field v-model="yarnBatchNo" name="yarnBatchNo" label="纱线批号" placeholder="请输入"
          :rules="[{ required: true, message: '请填写纱线批号' }]">
          <!--        && materialList > 1-->
          <template v-if="form.yarnBatchNo && materialList.length > 1" #button>
            <van-button size="mini" type="primary" @click="openPopup('material')">物料/客户</van-button>
          </template>
        </van-field>
        <van-field v-model="form.customerName" label="供应商" name="customerName" center clearable readonly
          placeholder="请先输入“纱线批号”查询" />

        <van-field v-model="form.materialDescribe" name="materialDescribe" label="物料信息" readonly
          placeholder="请先输入“纱线批号”查询" :rules="[{ required: false, message: '请选择物料' }]" />
        <!--        totalWgt-->



        <van-field name="isSelected" label="是否精选">
          <template #input>
            <van-radio-group v-model="form.isSelected" direction="horizontal" disabled>
              <van-radio v-for="dict in dictOpts.selectOpts" :key="dict.dictValue" :name="dict.dictValue">{{
                dict.dictLabel }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field v-if="form.isSelected === '2'" name="isSelected" label="红蓝箱"
          :rules="[{ required: form.isSelected === '2', message: '请选择红蓝箱' }]">
          <template #input>
            <van-radio-group v-model="form.isSelected" direction="horizontal">
              <van-radio v-for="dict in dictOpts.redBlueOpts" :key="dict.dictValue" :name="dict.dictValue">{{
                dict.dictLabel }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="autoHandle" label="是否自动挂纱">
          <template #input>
            <van-radio-group v-model="form.autoHandle" direction="horizontal">
              <van-radio v-for="dict in dictOpts.yesOrNoOpts" :key="dict.dictValue" :name="dict.dictValue">{{
                dict.dictLabel }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-row>
          <van-col span="12">
            <van-field v-model="form.grainWeight" label="粒重" name="grainWeight" center clearable disabled
              :rules="[{ required: false, message: '请输入粒重' }]" />
          </van-col>
          <van-col span="12">
            <van-field v-model="form.totalWgt" label="总重" name="totalWgt" center clearable readonly />
          </van-col>
        </van-row>


        <van-field name="silkNum" label="单托粒数" :rules="[{ required: true, message: '请输入单托粒数' }]">
          <template #input>
            <van-stepper v-model="form.silkNum" :min="1" integer input-width="70px" />
          </template>
        </van-field>

        <template v-if="form.yarnBatchNo && materialList.length > 0">
          <van-card style="padding: 8px">
            <template #title>
              <div class="van-cell required">上送接驳位</div>
            </template>

            <template #desc>
              <van-field name="comeLocationList" label="" class="" :rules="[{ required: true, message: '请选择上送接驳位' }]">
                <template #input>
                  <van-checkbox-group v-model="form.comeLocationList" class="w-100 ma-0 custom-checkbox"
                    direction="horizontal" @change="onComeChange">

                    <div v-for="(item, index) in comeLocation" :key="index">
                      <div>
                        <van-row v-for="value in item.locationRets">
                          <van-col span="3" v-for="valuse in value.locationRets">
                            <van-checkbox :name="valuse.locationCode" :disabled="valuse.state != 10">
                              {{ valuse.locationName.split('_')[1] }}
                              <template #icon="props">
                                <div class="pos-rel">
                                  <div class="checkbox-svg keep-px"
                                    :style="'background:' + handleWarehouseColor(props.checked, valuse.state, valuse.state !== '10' || !isSpecify)">
                                    <van-icon v-show="!!props.checked" name="success" size="10" />
                                  </div>
                                </div>
                              </template>
                            </van-checkbox>
                          </van-col>
                        </van-row>
                      </div>

                      <!--                        :disabled="item.state !== '20'" -->

                    </div>

                  </van-checkbox-group>
                </template>
              </van-field>
            </template>
          </van-card>

          <van-field v-if="form.materialType" name="floor" label="上送目的楼层" :border="false">

            <template #input>
              <van-radio-group v-model="form.floor" direction="horizontal">
                <van-radio v-for="dict in floorList" :key="dict.dictValue" :name="dict.dictValue"
                  :disabled="form.materialType === '1'">{{ dict.dictLabel }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <div style="display: flex;align-items: center;">


            <van-field style="flex-wrap: nowrap;width: 37%;" v-if="form.materialType" label="是否指定库位" :border="false">
              <template #input>
                <div class="flex-row-sb-c w-100">
                  <van-checkbox v-model="isSpecify"></van-checkbox>
                </div>
              </template>
            </van-field>

            <div style="display: flex;align-items: center;gap: 10px;padding: 15px;width: 64%;;">
              <div style="display: flex;align-items: center;" v-for="value in TypeList">
                <div class="child" :style="'background:' + value.color"></div>
                <div style="padding-left: 3px;font-size: 12px;">{{ value.label }}</div>
              </div>
            </div>

          </div>


          <template v-if="form.materialType">

            <van-card style="padding: 8px">
              <template #title>
                <div class="van-cell required">上送目的库位</div>
              </template>

              <template #desc>
                <van-field name="toLocationList" >
                  <template #input>
                    <van-checkbox-group v-model="form.toLocationList" class="w-100 ma-0 custom-checkbox"
                      direction="horizontal">

                      <div v-for="(item, index) in toLocation" :key="index">
                        <div style="display: flex;justify-content: left;flex-wrap: wrap;gap: 10px;">
                          <div v-for="value in item.locationRets">
                            <van-checkbox v-for="valuse in value.locationRets" :name="valuse.locationCode"
                              :disabled="valuse.state != 10">
                              {{ valuse.locationName.split('_')[1] }}
                              <template #icon="props">
                                <div class="pos-rel">
                                  <div class="checkbox-svg keep-px"
                                    :style="'background:' + handleWarehouseColor(props.checked, valuse.state, valuse.state !== '10' || !isSpecify)">
                                    <van-icon v-show="!!props.checked" name="success" size="10" />
                                  </div>
                                </div>
                              </template>
                            </van-checkbox>
                          </div>
                        </div>

                        <!--                        :disabled="item.state !== '20'" -->

                      </div>

                    </van-checkbox-group>
                  </template>
                </van-field>
              </template>
            </van-card>

          </template>
        </template>
      </van-form>
    </div>
    <div class="footer-bar flex-row">
      <van-button square type="primary" :disabled="btnDisabled" block @click="onSubmit">提交</van-button>
    </div>
    <!--   de-picker  -->
    <de-picker ref="customerPicker" v-model="popupShow" :request="getMaterialList" :queryParams="customerParams"
      :pagination="null" @onConfirm="onCustomerConfirm">

      <template #header="{ searchForm }">
        <div class="text-c  py-10  custom-tit">
          选择物料
          <van-button class="pos-ab top-7 right-15" type="primary" size="mini"
            @click="onPopupSearch(searchForm)">搜索</van-button>
        </div>
        <div class="flex-row">
          <van-field v-model="searchForm.materialNo" label="物料编码" placeholder="请输入" />
          <van-field v-model="searchForm.materialDescribe" label="物料描述" placeholder="请输入" />
        </div>
      </template>

      <template #listItem="{ scope }">
        <van-card>
          <template #title>
            <div class="w-100 flex-row-sb-c">
              <span>{{ scope.materialDescribe }}</span>
              <span>{{ scope.materialNo }}</span>
            </div>
          </template>

          <template #desc>
            <div class="w-100 text-l">
              <div>客户：{{ scope.customerName || '--' }}</div>
              <div>客户编码：{{ scope.customerName || '--' }}</div>
            </div>
          </template>
        </van-card>
      </template>
    </de-picker>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, computed, onMounted, onBeforeMount, inject, watch, provide, customRef } from 'vue';
import { showConfirmDialog, showDialog, closeDialog, showNotify, Toast } from 'vant';
import { getMaterialList, getLocationList, subMaterialTask } from '@/api/mes'
import { getDict } from '@/api/common'

import { useRouter } from 'vue-router';
import useStore from '@/store/index';
import { toFixed } from "postcss-px-to-viewport-8-plugin/lib/utils.js";
import { getWmsLocationList } from '../../api/pda';

const { user } = useStore();
const { roles } = user;
const the_loading = inject('the-loading');
const LOADING = inject('LOADING');
const router = useRouter();
const materialKeys = ['grainWeight', 'sourceType',
  'isSelected', 'materialDescribe', 'materialNo', 'materialType', 'factoryNo', 'customerNo', 'customerName']
const TypeList = ref([{
  label: '占用',
  value: '1',
  color: 'green'
}, {
  label: '锁定',
  value: '2',
  color: 'yellow'
}, {
  label: '空闲',
  value: '3',
  color: 'darkgray'
}, {
  label: '异常',
  value: '4',
  color: 'orange'
}, {
  label: '禁用',
  value: '5',
  color: 'red'
}
])
/**
 * 数据部分
 */

const materialList = ref([]) // 物料/客户信息列表数据
const customerParams = reactive({}) // 物料/客户信息查询参数
const yarnBatchNo = debounceRef('', 1000); // 纱线编号（防抖监听）
const formRef = ref(null);
const form = ref({
  yarnBatchNo: '',
  autoHandle: '0',
  comeLocationList: [],
  toLocationList: [],
  floor: '',
  customerName: '',
  materialDescribe: '',
  isSelected: '1',
  redBlueFlag: '',
  silkNum: 1,
  totalWgt: 0,
  grainWeight: 0,
  materialType: ''
}) // 表单提交数据
const dictOpts = reactive({
  selectOpts: [], //是否精选 字典项
  redBlueOpts: [],// 红蓝箱 字典项
  yesOrNoOpts: [],// 是、否 字典项
  floorOpts: [],// 楼层字典项
})
const floorList = computed(() => {
  return dictOpts.floorOpts.filter((item) => {
    if (form.value.materialType === '1') {
      return item.dictValue === '2'
    } else {
      return ['3', '4'].includes(item.dictValue)
    }
  })
})

const computedVal = computed(() => {
  return [form.value.silkNum, form.value.grainWeight]
})
const isSpecify = ref(true)
const popupShow = ref(false)
const btnDisabled = ref(false)
const comeLocation = ref([])
const toLocation = ref([])

/**
 * 元素ref
 */
const customerPicker = ref()

onBeforeMount(() => {
  getDicts('selected_flag', 'selectOpts')
  getDicts('red_blue_flag', 'redBlueOpts')
  getDicts('MES_YES_NO', 'yesOrNoOpts')
  getDicts('MES_FTY_FLOOR', 'floorOpts')
})

onMounted(() => { });

watch(
  () => [yarnBatchNo.value, computedVal.value],
  async ([n1, n2], [o1, o2]) => {
    if (n1 && n1 != o1) {
      customerParams.yarnBatchNo = n1;
      form.value.yarnBatchNo = n1;
      await queryMaterialInfo()
    }

    const allTight = n2.every((item) => {
      return !isNaN(item)
    });
    console.log(allTight, n2);
    if (allTight) {
      form.value.totalWgt = Number((n2[0] * n2[1]).toFixed(2))
    }

  }, { deep: false }
);
watch(
  () => [form.value.floor],
  async ([n1, n2], [o1, o2]) => {
    await queryLocationList('COME')
    await getWmsLocationListS()

  }, { deep: false }
);

// 来源库位选择事件
function onComeChange(val) {
  // const c_ind = [];
  // // 获取下标
  // val.forEach((v) => {
  //   c_ind.push(comeLocation.value.flatMap(item => item.locationRets).findIndex((item) => item.locationCode === v));
  // })

  // if (!isSpecify.value) {
  //   // 如果去向库位有对应下标的数据 则自动选中
  //   c_ind.forEach((i) => {
  //     toLocation.value[i] && form.value.toLocationList.push(toLocation.value[i].locationCode)
  //   })
  // }

}


function handleWarehouseColor(checked, state, dis) {
  if (checked) {
    return 'rgb(25, 137, 250)'
  }

  const config = {
    '20': 'green',
    '50': 'yellow',
    '10': 'darkgray',
    '30': 'orange',
    '40': 'red',
  }
  return config[state]
}

function debounceRef(value, delay) {
  let timer = null;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newValue) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          value = newValue;
          trigger();
        }, delay);
      }
    };
  });
}

function onPopupSearch(form) {
  customerPicker.value.onSearch()
}

function openPopup(t) {
  popupShow.value = true;
}

async function onSubmit() {
  console.log(isSpecify.value)
  
  function customSort(a, b) {
    // 使用正则表达式提取两个数字部分
    const regex = /-(\d+)-(\d+)$/;
    const [, numA1, numA2] = a.match(regex).map(Number);
    const [, numB1, numB2] = b.match(regex).map(Number);

    // 先比较第一个数字（组排序）
    if (numA1 !== numB1) {
      return numA1 - numB1;
    }
    // 如果第一个数字相同，比较第二个数字（组内排序）
    return numA2 - numB2;
  }
  formRef.value.validate()
    .then(async () => {
      try {
        if(isSpecify.value && form.value.toLocationList.length === 0){
          showNotify({ type: 'danger', message: `“上送目的库位” 不能为空`, duration: 3000 });
          return
        }
        if (form.value.comeLocationList.length !== form.value.toLocationList.length && isSpecify.value) {
          showNotify({ type: 'danger', message: `“上送接驳位” 和 “上送目的库位” 数量不一致`, duration: 3000 });
          return
        }
        const params = { ...form.value, taskType: 'WGYS', isLocation: isSpecify.value ? '1' : '0', comeLocationList: form.value.comeLocationList.sort(customSort), toLocationList: form.value.toLocationList.sort(customSort) };
        await subMaterialTask(params)
        showNotify({ type: 'success', message: '提交成功', duration: 3000 });
        init()
        form.value.yarnBatchNo = ''
      } finally {
      }
    })
    .catch(e => {
      console.log(e);
    });
}
async function getWmsLocationListS(){
   if (!form.value.materialType) return
   const { data } = await getWmsLocationList({
    floor: form.value.floor,
    isMaterial: 'M',
    locationCode:form.value.materialType == '1'?'AZ':'JZ'
  })
  toLocation.value = !!data ? data : []
}
// 查询上送接驳位
async function queryLocationList(type) {
  if (!form.value.materialType) return

  try {
    const { data } = await getLocationList({
      taskType: 'WGYS',
      factoryNo: 1100,
      materialType: form.value.materialType,
      locationType: type,
      floor: type === 'COME' ? undefined : form.value.floor,
    });


    if (type === 'TO') {
      toLocation.value = !!data ? data : []
    } else {
      comeLocation.value = !!data ? data : []
    }

  } catch (error) {
    console.log(error);
  }
}

const init = () => {
  form.value.customerName = ''
  form.value.autoHandle = '0'
  form.value.comeLocationList = []
  form.value.toLocationList = []
  form.value.floor = null
  form.value.materialType = ''
  form.value.customerName = ''
  form.value.materialDescribe = ''
  form.value.isSelected = '1'
  form.value.redBlueFlag = ''
  form.value.silkNum = 1
  form.value.totalWgt = 0
  form.value.grainWeight = 0
  materialList.value = []
}
// 根据纱线批号查询物料信息（包括供应商信息）
async function queryMaterialInfo() {
  try {
    const { data } = await getMaterialList({ yarnBatchNo: customerParams.yarnBatchNo });
    init()


    if (data?.length) {
      materialKeys.forEach(k => {
        form.value[k] = data[0][k] || ''
      })
      materialList.value = data || []
    }
    if (form.value.materialType === '2') {
      form.value.floor = '4'
    } else if (form.value.materialType === '1') {
      form.value.floor = '2'
    }
    if ([null, undefined, ''].includes(data[0].grainWeight)) {
      form.value.totalWgt = '--'
    } else if (data[0].grainWeight === 0) {
      form.value.totalWgt = 0
    } else {
      form.value.totalWgt = data[0].grainWeight * (data[0].silkNum || 0)
    }
  } catch (e) {
    console.log(e)
  }
}

// 选择物料/供应商信息
function onCustomerConfirm(data) {
  // materialKeys.forEach(k => {
  //   form.value[k] = data[k] || ''
  // })
  queryLocationList('COME')
  getWmsLocationListS()
}

// 字典查询
async function getDicts(code, key) {
  try {
    const { data } = await getDict(code);
    dictOpts[key] = data || []
  } catch (error) {
    console.log(error)
  }
}

</script>
<style scoped lang="scss">
.container {
  display: flex;
  /* grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); */
  gap: 10px;
  /* padding: 10px; */
  flex-wrap: wrap;
}

.item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-out {
  width: 20px;
  height: 20px;
}

.van-grid {
  width: 100%;
  background-color: #fff;
}

.swipe {
  height: 25vh;
}

.custom-tit {
  background: #f5f5f5;
}

.van-checkbox-group {
  font-size: 12px;
}

.field-label::after {
  border: 0;
}

.van-row {
  gap: 10px;
}

.van-card:not(:first-child) {
  margin-top: 0 !important;
}

.required::before {
  margin-right: 2px;
  color: var(--van-field-required-mark-color);
  content: "*";
}

.van-cell-group--inset {
  margin: 0 !important;

  .van-cell {
    padding: 10px 0 !important;
  }
}

.child {
  width: 10px;
  height: 10px;
  background: #f2f3f5;
  border-radius: 4px;
}

.childPower {
  width: 40px;
  height: 40px;
  background: #f2f3f5;
  border-radius: 4px;
}

.childText {
  text-align: center;
  font-size: 12px;
}

.custom-checkbox {
  .van-grid-item__content {
    padding: 0
  }

  .van-checkbox__icon--checked .van-icon {
    border-color: transparent;
    background-color: transparent;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  :deep(.van-grid-item__content) {
    padding: 0 !important;
  }

  .checkbox-svg {
    width: 22px;
    height: 22px;

    svg {
      background-color: #13b058;
    }
  }

  .van-checkbox {
    //display: block;
    margin-right: 0;
    margin-bottom: 10px;
    flex-direction: column;
    align-items: center;

    :deep(.van-checkbox__label) {
      margin-left: 0 !important;
    }
  }
}

.checkbox-cell {
  padding: 0 16px !important;
  height: 30vh;
  overflow-y: auto;
}

.legend-item {
  line-height: normal;

  .l-item {
    width: 14px;
    height: 14px;
    background: #616161;
    display: inline-block;

    &.success {
      background: #13b058;
    }

    &.warning {
      background: orange;
    }
  }
}

:deep(.van-swipe-item) {
  img {
    height: 100%;
  }
}

:deep(.van-card__thumb) {
  height: 50px;
}

:deep(.van-card__content) {
  min-height: 50px;
}

:deep(.van-card__num) {
  float: left;
}

.menu-icons {
  font-size: 14px;
  width: 45vw;
  height: 10vh;
}

.text-nowrap {
  //margin-top: -10px;
}

.van-grid {
  display: block;
}

// .content {
//   background: url('@/assets/images/home-bg.png');</style>
